package cn.whdream.juc;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 线程池：提供一个线程队列。避免了创建和销毁额外的开销，提高响应的速度。
 * @author admin
 *
 */
public class TestScheduledThreadPool {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
		ThreadDemo demo = new ThreadDemo();
		for (int i = 0; i < 10; i++) {
			Future<Integer> future =  pool.schedule(demo, 2, TimeUnit.SECONDS);
			System.out.println("result:"+future.get());
		}
		pool.shutdown();
	}
	
	private static class ThreadDemo implements Callable<Integer>{

		private int i;

		@Override
		public Integer call() throws Exception {
			i = new Random().nextInt(100);
			System.out.println("Thread"+Thread.currentThread().getName()+" num:");
			return i;
		}
		
	}
}
  